import 'package:core_package/ui/appbar/my_appbar.dart';
import 'package:core_package/ui/loadding_or_toast/loadding.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_app_unionad/view_model/page_manager_view_model.dart';

import 'dart:io';

import 'package:webview_flutter/webview_flutter.dart';

class WebPage extends StatefulWidget {
  static const routeName = "/WebPage";
  final String? url;
  final String? title;
  final bool isSplash;

  WebPage({
    this.url,
    this.title,
    this.isSplash = false,
  });

  @override
  _WebPage createState() => _WebPage();
}

class _WebPage extends State<WebPage> {
  int index = 0;
  late WebViewController _controller;

  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (Platform.isAndroid) {
          if (widget.isSplash) {
            PagesManagerViewModel.splashUpdateType(context);
          } else {
            return true;
          }
        }
        return false;
      },
      child: Scaffold(
        appBar: MyAppBar(context, title: widget.title ?? '', backFunction: () {
          if (widget.isSplash) PagesManagerViewModel.splashUpdateType(context);
        }),
        body: IndexedStack(
          index: index,
          children: [
            Center(
              child: ProgressDialog.showFirstLoading(),
            ),
            Column(
              children: [
                Expanded(
                  child: WebView(
                    initialUrl: widget.url,
                    onPageFinished: (url) {
                      setState(
                        () {
                          index = 1;
                        },
                      );
                    },
                    onWebViewCreated: (controller) {
                      _controller = controller;
                    },
                    onPageStarted: (str) {},
                    javascriptMode: JavascriptMode.unrestricted,
                    onWebResourceError: (err) {},
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
}
